package com.cjl.multi_thread.share_cooperate;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

public class MyForkJoinTask extends RecursiveAction {

    private File path;

    public MyForkJoinTask(File path) {
        this.path = path;
    }

    @Override
    protected void compute() {
        File[] files = path.listFiles();
        List<MyForkJoinTask> subTasks = new ArrayList<>();
        for (File file : files) {
            if (file.isDirectory()){
                subTasks.add(new MyForkJoinTask(file));
            }else {
                if (file.getAbsolutePath().endsWith(".java")){
                    System.out.println("MyForkJoinTask.compute "+file.getAbsolutePath());
                }
            }
        }

        if (!subTasks.isEmpty()){
            for (MyForkJoinTask myForkJoinTask : invokeAll(subTasks)) {
                myForkJoinTask.join();//等待子任务完成
            }
        }
    }

    public static void main(String[] args) throws Exception{
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        MyForkJoinTask myForkJoinTask = new MyForkJoinTask(new File("/home/battlecall/IdeaProjects/RunJavaMaster/src/main/java/com/cjl/annotation"));
        forkJoinPool.execute(myForkJoinTask);

        System.out.println("MyForkJoinTask.main Start");
        
        Thread.sleep(1);
        int otherWork = 0;
        for (int i = 0; i < 100; i++) {
            otherWork += i;
        }
        System.out.println("MyForkJoinTask.main ,otherWork="+otherWork);
        myForkJoinTask.join();//阻塞方法
        System.out.println("MyForkJoinTask.main End");



    }
}
